package com.by.utils;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Hzy
 * @version 1.0
 * @date 2025/4/14  20:21
 * @description
 * @since jdk11
 */
@Component
public class ACode {
    private static final AtomicInteger currentNumber = new AtomicInteger(1);
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

    // 生成支付单号的方法
    public static Long generatePaymentNumber() {
        try {
            // 获取当前日期
            LocalDate now = LocalDate.now();
            // 格式化日期
            String yearMonthDay = now.format(formatter);
            // 格式化编号为 4 位，不足 4 位前面补 0
            String formattedNumber = String.format("%04d", currentNumber.getAndIncrement());
            // 拼接支付单号
            return Long.parseLong(yearMonthDay + formattedNumber);
        } catch (NumberFormatException e) {
            System.err.println("生成支付单号时发生错误: " + e.getMessage());
            return null;
        }
    }

    // 每月 1 号 0 点重置编号
    @Scheduled(cron = "0 0 0 * * ?")
    public void resetNumber() {
        currentNumber.set(1);
    }
}
